package com.mystudio.android.calendar.adaptor;

import java.util.List;

import android.content.Context;
import android.text.format.Time;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import com.mystudio.android.calendar.R;
import com.mystudio.android.calendar.constants.Constants;
import com.mystudio.android.calendar.model.Instance;
import com.mystudio.android.util.Logger;

/**
 * Position here refers to the number of weeks count from the week of 0 Julian day (assume week start from Sunday)  
 */
public class DaySummaryAdapter extends ArrayAdapter<Instance> {
	private static final Logger logger = new Logger(Constants.LOG_TAG, DaySummaryAdapter.class);
	private int mViewResourceId;
	private List<Instance> mInstances;
	private LayoutInflater mInflater;
	private String allDay = (String)getContext().getResources().getText(R.string.all_day);
	private Time tempTime = new Time();
	
	public DaySummaryAdapter(Context context, int viewResourceId, List<Instance> instances) {
		super(context, viewResourceId, instances);
		this.mViewResourceId = viewResourceId;
		this.mInstances = instances;
	}
	
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View v = convertView;
		if (v == null) {
			if (mInflater == null) {
				mInflater = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			}
			v = mInflater.inflate(mViewResourceId, null);
		}
		
		Instance instance = mInstances.get(position);

		if (instance != null) {
			TextView timeText = (TextView)v.findViewById(R.id.daySummaryRowTime);	
			TextView descText = (TextView)v.findViewById(R.id.daySummaryRowDesc);
logger.info(instance.title + ":" + instance.allDay);			
			if ("1".equals(instance.allDay)) {
				timeText.setText(allDay);
			} else {
				timeText.setText(getTimeRangeStr(Long.parseLong(instance.begin)));
			}
			descText.setText(instance.title);
			descText.setTextColor(instance.color);
		}
		
		return v;
	}
	
	public void setItems(List<Instance> instances) {
		this.mInstances = instances;
	}
	
	private String getTimeRangeStr(long begin) {
		StringBuffer range = new StringBuffer();
		tempTime.set(begin);
		range.append(tempTime.hour).append(":").append(tempTime.minute).append(" - "); 
		//tempTime.set(end);
		//range.append(tempTime.hour).append(":").append(tempTime.minute);
		
		return range.toString();
	}
}
